import React, { Component } from 'react'
import { Spin } from 'antd'
import NavigationBar from '@/components/viewWidget/NavigationBar'
import Avatar from '@/components/viewWidget/Avatar'
import { Link } from "react-router-dom";
import logo from './static/logo.png'
import {
  HomeFilled, ProfileOutlined, QuestionCircleFilled, CustomerServiceFilled, ShoppingFilled, ProfileFilled,
  WifiOutlined, StarFilled, TeamOutlined, EditFilled, CompassFilled, LogoutOutlined
} from '@ant-design/icons'
import paramUtil from '@/utils/paramUtil.js'
import { message } from 'antd'
import { Outlet } from 'react-router-dom'
import moment from 'moment'
import { get, post } from '@/utils/requestUtil.js'
import { withRouterContext } from '@/context/router/routerContext.js'
import './index.css'
import MessageController from '@/components/viewWidget/Message/MessageController';
import MessageBadge from '@/components/viewWidget/Message/MessageBadge';
import { getContext } from '@/context/common/applicationContext'
import consoleUtil from '@/utils/consoleUtil';

class Home extends Component {

  constructor(props) {
    super(props)
    this.state = {
      loading: true,
      navItem: [],
      user: {},
      userMessage: {}, //当前用户的消息
      prompts: null, //导航栏提示语
      mobileMenuDisplay: false //手机端菜单显隐
    }
  }

  onSearch = async (event) => {
    if (event) {
      event.preventDefault()
    }
    message.success('查询操作')
  }

  doLogout = async () => {
    const response = await post('/auth/doLogout')
    if (response && response.data) {
      if (response.data === true) {
        localStorage.removeItem('token')
        this.props.navigate('/login')
      }
    }
  }

  async componentDidMount() {
    //获取时间段提示语参数
    const param = await paramUtil.get('timePrompts')
    const hour = moment().format('HH') //当前时间取小时
    let prompts = '' //提示语
    if (param && Array.isArray(param.children) && param.children.length > 0) {
      const paramItem = param.children.find(item => item.code === hour)
      if (paramItem) {
        const contentArr = paramItem.content.split('；')
        const randomIndex = Math.floor(Math.random() * contentArr.length)
        prompts = contentArr[randomIndex]
      }
    }

    //获取当前登陆用户的信息
    const response = await get('/customer/getCurrentCustomer')
    let user = response && response.data ? response.data : {}

    //获取当前用户的消息
    await this.getCurrentUserMessage()

    //导航栏配置项
    let navItem = await this.renderNavItem(prompts, user)

    await new Promise(resolve => {
      this.setState({
        navItem,
        user,
        prompts
      }, () => {
        this.props.setContextValue && this.props.setContextValue({
          user,
          updateUserInfo: this.updateUserInfo,
          updateUserMessage: this.updateUserMessage,
        })
        resolve()
      })
    })

    await new Promise(resolve => { this.setState({ loading: false }, resolve) })
  }

  //用户信息变化
  updateUserInfo = async (user) => {
    let navItem = await this.renderNavItem(this.state.prompts, user)
    await new Promise(resolve => {
      this.setState({
        navItem,
        user
      }, () => {
        this.props.setContextValue && this.props.setContextValue({ user })
        resolve()
      })
    })
  }

  //用户消息发生变化
  updateUserMessage = async () => {
    const oldUnreadMessageNumber = this.state.userMessage.unreadMessage ? this.state.userMessage.unreadMessage.length : 0
    await this.getCurrentUserMessage()
    const newUnreadMessageNumber = this.state.userMessage.unreadMessage ? this.state.userMessage.unreadMessage.length : 0
    //只有未读消息数量不相等的时候才需要重新挂载导航栏
    if (oldUnreadMessageNumber !== newUnreadMessageNumber) await this.reRenderNavItem()
  }

  //移动端导航菜单栏点击事件
  mobileMenuItemOnClick = async () => {
    //step.1 改变导航栏菜单显隐
    await new Promise(resolve => { this.setState({ mobileMenuDisplay: !this.state.mobileMenuDisplay }, resolve) })
    await this.reRenderNavItem()
  }

  //导航栏内容组装
  renderNavItem = async (prompts, user) => {
    let navItem = [
      { key: '1', content: <Link to='/'><img src={logo} style={{ height: '100%' }} alt='logo' /></Link>, className: 'mobile-none' },
      { key: '98', content: <Link to='/' style={{ height: '30%' }}><img src={logo} style={{ height: '100%' }} alt='logo' /></Link>, className: 'mobile-display' },
      {
        key: '99',
        content:
          <div className='home-mobile-menu'>
            <span onClick={this.mobileMenuItemOnClick}>
              <ProfileFilled /> 菜单
            </span>
            {
              this.state.mobileMenuDisplay === true ?
                <div className='home-mobile-menu-content'>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><HomeFilled /> 首页</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><CompassFilled /> 新闻</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><QuestionCircleFilled /> 博问</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><CustomerServiceFilled /> 学习园区</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><ShoppingFilled /> 会员</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><WifiOutlined /> 动态</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><StarFilled /> 收藏</Link>
                  <Link to='/' onClick={this.mobileMenuItemOnClick}><TeamOutlined /> 好友</Link>
                  <Link to='/write/blog' onClick={this.mobileMenuItemOnClick}><EditFilled /> 写博客</Link>
                  <Link to={`/user/${user.id}`} onClick={this.mobileMenuItemOnClick}><ProfileOutlined /> 我的博客</Link>
                </div> : ''
            }
          </div>,
        className: 'mobile-display'
      },
      { key: '2', content: <Link to='/'><HomeFilled /> 首页</Link>, className: 'mobile-none' },
      { key: '3', content: <Link to='/'><CompassFilled /> 新闻</Link>, className: 'mobile-none' },
      { key: '4', content: <Link to='/'><QuestionCircleFilled /> 博问</Link>, className: 'mobile-none' },
      { key: '5', content: <Link to='/'><CustomerServiceFilled /> 学习园区</Link>, className: 'mobile-none' },
      { key: '6', content: <Link to='/'><ShoppingFilled /> 会员</Link>, className: 'mobile-none' },
      { key: '8', content: <Link to='/'><WifiOutlined /> 动态</Link>, className: 'mobile-none' },
      { key: '9', content: <Link to='/'><StarFilled /> 收藏</Link>, className: 'mobile-none' },
      { key: '10', content: <Link to='/'><TeamOutlined /> 好友</Link>, className: 'mobile-none' },
      { key: '11', content: <Link to='/write/blog'><EditFilled /> 写博客</Link>, className: 'mobile-none' },
      { key: '12', content: <Link to={`/user/${user.id}`}><ProfileOutlined /> 我的博客</Link>, className: 'mobile-none' },
      { key: '13', content: <span>{prompts}</span>, className: 'mobile-none', style: { maxWidth: '25vw' } },
      {
        key: '14',
        content: <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}>
          <MessageBadge style={{ marginRight: '30px' }}></MessageBadge>
          <Avatar
            key={user.avatarUrl}
            src={user.avatarUrl}
            alt='avatar'
            isCircle={true}
            rotating={true}
            style={{ cursor: 'pointer' }}
            onClick={() => { this.props.navigate(`/personal/center/${this.state.user.id}`) }}
          ></Avatar>
          <div
            onClick={() => { this.props.navigate(`/personal/center/${this.state.user.id}`) }}
            style={{ paddingLeft: '1em', fontWeight: 'bolder', cursor: 'pointer' }}
          >
            {user.nickname}
          </div>
          <a
            href='!#'
            onClick={async (e) => {
              e.preventDefault()
              await this.doLogout()
            }}
            style={{ paddingLeft: '2em' }}
            title='登出'
          >
            <LogoutOutlined />
          </a>
        </div>,
        style: { flexGrow: 1, justifyContent: 'right', paddingRight: '2em' }
      }
    ]
    return navItem
  }

  //导航栏重组
  reRenderNavItem = async () => {
    let navItem = await this.renderNavItem(this.state.prompts, this.state.user)
    new Promise(resolve => {
      this.setState({
        navItem
      }, resolve)
    })
  }

  //获取当前用户的消息
  getCurrentUserMessage = async () => {
    const response = await get('/message/current/all')
    if (response && response.code === 200) {
      await new Promise(resolve => {
        this.setState({
          userMessage: response.data
        }, () => {
          this.props.setContextValue && this.props.setContextValue({ userMessage: response.data })
          resolve()
        })
      })
    } else {
      consoleUtil.error('消息获取失败', response)
    }
  }

  render() {
    if (this.state.loading === true) return <Spin />
    return (
      <div className='home-main'>
        <NavigationBar
          navItem={this.state.navItem}
        />
        <div style={{ marginTop: '60px' }}></div>
        <Outlet />
        <MessageController taskEnable={true} promptEnable={true} />
      </div>
    )
  }
}

export default getContext(withRouterContext(Home))
